package com.job51.hro.datacheckservice.service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.job51.hro.datacheckservice.dto.MailSendAndStatus;
import com.job51.hro.datacheckservice.dto.config.TiaojiNotice;
import com.job51.hro.datacheckservice.mapper.MailsendMapper;
import com.job51.hro.datacheckservice.util.DateUtil;
import com.job51.hro.datacheckservice.util.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.Date;
import java.util.List;

/**
 * 〈一句话功能简述〉<br>
 * 〈〉
 *
 * @author pengfei.ma
 * @since 1.0.0
 */
@Service
public class TJMailServiceImpl implements TJMailService {
    @Autowired
    MailsendMapper mailsendMapper;

    @Autowired
    TiaojiNotice tiaojiNotice;

    @Autowired
    JavaMailSenderImpl sender;

    static final Logger log = LoggerFactory.getLogger(TJMailService.class);

    private String mailFileLoc;

    @Override
    public int sendTJCheckMail() {
        String date = DateUtil.getString(new Date(System.currentTimeMillis() - 1000 * 60 * 60 * 24),"yyyyMMdd");
        List<MailSendAndStatus> mailSendAndStatusList = mailsendMapper.selectMailAndStatus(date);
        if(mailSendAndStatusList == null || mailSendAndStatusList.isEmpty()){
            return 0;
        }
        String filePath = tiaojiNotice.getTmpExcel().getPath() + "/" + FileUtil.specialSignReplace(tiaojiNotice.getTmpExcel().getFileName()) + ".xlsx";
        this.mailFileLoc = filePath;
        try {
            this.generateExcel(mailSendAndStatusList, filePath);
            this.sendMail(Boolean.TRUE);
        } catch (Exception e) {
            log.error(e.getMessage());
            return  -1;
        }
        return  1;
    }

    /**
     * 生成excel
     *
     * @param list，该list是需要的数据
     */
    private void generateExcel(List<MailSendAndStatus> list, String path) {
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        //字体大小
        WriteFont headWriteFont = new WriteFont();
        headWriteFont.setFontHeightInPoints((short) 10);
        headWriteCellStyle.setWriteFont(headWriteFont);
        HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                new HorizontalCellStyleStrategy(headWriteCellStyle, (WriteCellStyle) null);

        //生成文件
        EasyExcel.write(path, MailSendAndStatus.class).registerWriteHandler(horizontalCellStyleStrategy).sheet("sql结果").doWrite(list);
        //生成流
        //EasyExcel.write(out, WorkDetails.class).registerWriteHandler(horizontalCellStyleStrategy).sheet("name").doWrite(list);
    }

    private void sendMail(Boolean deleteFile) throws MessagingException {
        String attachPath = this.mailFileLoc;
        File file = new File(attachPath);
        if(!file.exists()){
            throw new RuntimeException("Excel文件不存在");
        }
        MimeMessage mimeMessage = sender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        helper.setFrom(tiaojiNotice.getMail().getFrom());
        helper.setTo(tiaojiNotice.getMail().getTo());
        helper.setSubject(tiaojiNotice.getMail().getSubject());
        helper.setText("Just do it !");
        String attachName = attachPath.substring(attachPath.lastIndexOf("/")+1);
        helper.addAttachment(attachName, file);
        sender.send(mimeMessage);
        if(deleteFile){
            boolean exist = file.delete();
            if(!exist){
                throw new RuntimeException("删除Excel文件失败");
            }
        }
    }

}
